import validate from './validate'

let defaultOption = {
  isBeforeSure: true, // 提交前是否显示确认弹框
  isShowSuccessMsg: true, // 是否提示成功文字弹框
  confirmText: '确定', // 确认弹框按钮文字信息
  beforeMsg: '确认是否继续此操作?', // 保存前的提示信息
  loadingMsg: '', // 加载中提示信息
  successMsg: '保存成功', // 成功的提示信息
  errorMsg: '保存失败', // 失败的提示信息
  validate: true,
  validateRule: {}
}
// 表单保存处理器
export default async function handle(saver, formData, option) {
  option = Object.assign(defaultOption, option)
  if (option.validate) { // 需要表单验证
    const validResult = await validate(formData, option.validateRule)
    if (validResult.validError) {
      // 验证有错误
      console.warn('验证有错误', validResult)
      wx.showToast({
        title: validResult.errFields[0].errMsg,
        icon: 'none',
        duration: 3000
      })
      return Promise.reject(validResult)
    }
  }
  if (saver.loading) return Promise.reject('用户重复点击')
  if (option.isBeforeSure) { // 确认的提示
    const res = await wx.showModal({
      title: '提示',
      content: option.beforeMsg
    })
    if (res.cancel) return Promise.reject('用户取消提交')
  }
  saver.loading = true
  wx.showLoading({
    title: option.loadingMsg,
    mask: true
  })
  const showErrorFun = (msg, e) => {
    wx.showToast({
      title: msg || option.errorMsg,
      icon: 'none',
      duration: 3000
    })
    delete saver.loading
    return Promise.reject(e)
  }
  let response = await saver(formData).catch(e => showErrorFun(null, e))
  wx.hideLoading()
  if (response.meta.status !== 'success') {
    return showErrorFun(response.meta.message, response)
  }
  option.isShowSuccessMsg && await wx.showModal({
    title: '提示',
    content: option.successMsg instanceof Function ? option.successMsg(response) : option.successMsg,
    confirmText: option.confirmText instanceof Function ? option.confirmText(response) : option.confirmText,
    showCancel: false
  })
  delete saver.loading
  return response
}
